#include "logindialog.h"
#include "ui_logindialog.h"
#include "mainwindow.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QMessageBox>
#include <QCoreApplication>
#include <QTime>

loginDialog::loginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::loginDialog)
{
    ui->setupUi(this);
    initDb();
}

void loginDialog::initDb()
{
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/db06.db";

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);

    if(db.open()) {
        qDebug() << "数据库打开成功：" << dbPath;
        createTable();
    } else {
        qDebug() << "数据库打开失败：" << db.lastError();
    }
}

void loginDialog::closeDb()
{
    if(db.isOpen()) {
        db.close();
        qDebug() << "数据库已关闭";
    }
}

loginDialog::~loginDialog()
{
    closeDb();
    delete ui;
}

void loginDialog::createTable()
{
    if(!db.isOpen()) return;

    QStringList tables;
    tables << "CREATE TABLE IF NOT EXISTS users ("
              "id INTEGER PRIMARY KEY AUTOINCREMENT,"
              "name TEXT NOT NULL,"
              "password TEXT NOT NULL)";

    tables << "CREATE TABLE IF NOT EXISTS products ("
              "product_id INTEGER PRIMARY KEY AUTOINCREMENT,"
              "name TEXT NOT NULL,"
              "price REAL)";

    tables << "CREATE TABLE IF NOT EXISTS orders ("
              "order_id INTEGER PRIMARY KEY AUTOINCREMENT,"
              "user_id INTEGER NOT NULL,"
              "product_id INTEGER NOT NULL,"
              "total_price REAL NOT NULL,"
              "create_time DATETIME NOT NULL,"
              "FOREIGN KEY(user_id) REFERENCES users(id),"
              "FOREIGN KEY(product_id) REFERENCES products(product_id))";

    QSqlQuery query(db);
    foreach(const QString &sql, tables) {
        if(!query.exec(sql)) {
            qDebug() << "建表失败：" << query.lastError().text();
        }
    }

    insertTestData();
}

void loginDialog::insertTestData()
{
    if(!db.isOpen()) return;

    // 检查是否已有数据
    QSqlQuery checkQuery(db);
    checkQuery.exec("SELECT COUNT(*) FROM users");
    if(checkQuery.next() && checkQuery.value(0).toInt() > 0) {
        return; // 已有数据则不再插入
    }

    // 初始化随机数种子（Qt 5.3.1兼容方式）
    qsrand(QTime::currentTime().msec());

    QSqlQuery query(db);

    // 1. 插入用户数据
    query.exec("INSERT INTO users (name, password) VALUES ('admin', '123456')");
    query.exec("INSERT INTO users (name, password) VALUES ('user1', '111111')");

    // 2. 插入商品数据
    query.exec("INSERT INTO products (name, price) VALUES ('玫瑰', 199)");
    query.exec("INSERT INTO products (name, price) VALUES ('百合花', 159)");

    // 3. 插入30天的随机销售数据
    QDateTime now = QDateTime::currentDateTime();
    for(int i = 0; i < 30; ++i) {
        QString date = now.addDays(-i).toString("yyyy-MM-dd");

        // 生成随机销量（兼容Qt 5.3.1）
        int roseQty = 20 + (qrand() % 20);  // 20-39的随机数
        int lilyQty = 15 + (qrand() % 15);  // 15-29的随机数

        // 插入玫瑰订单
        query.exec(QString("INSERT INTO orders (user_id, product_id, total_price, create_time) "
                  "VALUES (1, 1, %1, '%2 08:00:00')")
                  .arg(roseQty * 199).arg(date));

        // 插入百合花订单
        query.exec(QString("INSERT INTO orders (user_id, product_id, total_price, create_time) "
                  "VALUES (1, 2, %1, '%2 10:00:00')")
                  .arg(lilyQty * 159).arg(date));
    }
}

void loginDialog::on_pushButtonLogin_clicked()
{
    QSqlQuery query(db);
    query.prepare("SELECT id FROM users WHERE name=? AND password=?");
    query.addBindValue(ui->lineEditUserName->text().trimmed());
    query.addBindValue(ui->lineEditPassword->text().trimmed());

    if(query.exec() && query.next()) {
        accept();  // 关闭对话框并返回Accepted
    } else {
        QMessageBox::warning(this, "错误", "用户名或密码错误");
    }
}

void loginDialog::on_pushButtonReg_clicked()
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO users (name, password) VALUES (?, ?)");
    query.addBindValue(ui->lineEditUserName->text().trimmed());
    query.addBindValue(ui->lineEditPassword->text().trimmed());

    if(query.exec()) {
        QMessageBox::information(this, "成功", "注册成功");
    } else {
        QMessageBox::warning(this, "错误", "注册失败：" + query.lastError().text());
    }
}
